package com.web.kdl.config.security.components;

import cn.hutool.core.util.StrUtil;
import com.web.kdl.common.result.CommonResult;
import com.web.kdl.common.result.ReturnCode;
import com.web.kdl.config.security.AuthConstants;
import com.web.kdl.util.JwtTokenUtil;
import com.web.kdl.util.RedisUtils;
import com.web.kdl.util.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.web.kdl.config.security.AuthConstants.REDIS_KEY_AUTH_TOKEN;

/**
 * @Author： shulibin
 * @Date： 2025/7/28 9:27
 * @Describe：
 */
@Slf4j
public class KdlLogoutSuccessHandler implements LogoutSuccessHandler {
    private final RedisUtils redisUtils;

    public KdlLogoutSuccessHandler(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        final String token = request.getHeader(AuthConstants.TOKEN_HEADER);
        // 1.请求头中没有携带token
        if (StrUtil.isBlank(token)) {
            ServletUtils.renderResult(response, CommonResult.success("没有登录信息，无需退出"));
            return;
        }

        // 携带token
//        final String token = authorization.replace(AuthConstants.TOKEN_PREFIX, "");
        String userId;
        // 2.提供的token异常
        try {
            userId = JwtTokenUtil.extractUserId(token);
        }catch (Exception e){
            log.error("YaLogoutHandler logout 解析jwt异常：{}", e.toString());
            ServletUtils.renderResult(response, new CommonResult<>(ReturnCode.UNAUTHORIZED.getCode(), "凭证异常"));
            return;
        }
        // 清空Redis
        redisUtils.delete(REDIS_KEY_AUTH_TOKEN + userId);
        log.info("YaLogoutSuccessHandler onLogoutSuccess");
        ServletUtils.renderResult(response, CommonResult.success("退出登录成功"));
    }
}
